package org.spring.springboot.config;

import org.spring.springboot.entity.Schedule;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

@Component
public class MyListenerProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    public static List<Schedule> scheduleList = new ArrayList<>(100); //保存国籍信息

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Method[] methods = ReflectionUtils.getAllDeclaredMethods(bean.getClass());
        if (methods != null) {
            for (Method method : methods) {
                ScheduleCron scheduleCron = AnnotationUtils.findAnnotation(method, ScheduleCron.class);
                if (null != scheduleCron) {
                    Schedule setting = Schedule.builder()
                            .cronKey(scheduleCron.scheduleKey())
                            .cronName(scheduleCron.cronName())
                            .cronExpression(scheduleCron.cronExpression())
                            .beanName(beanName)
                            .methodName(method.getName())
                            .valid("Y")
                            .operation("ADD")
                            .build();
                    scheduleList.add(setting);
                }
            }
        }
        return bean;
    }
}